package org.example.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.example.annotation.Log;
import org.example.domain.dto.DTO;
import org.example.domain.dto.ErpMaterialDTO;
import org.example.domain.po.*;
import org.example.domain.vo.ErpDepotItemVO;
import org.example.enums.BusinessType;
import org.example.service.*;
import org.example.service.impl.ErpMaterialServiceImpl;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/commodity/material")
@Api("/商品类别")
public class ErpMaterialController {

    @Autowired
    ErpMaterialServiceImpl erpMaterialServiceImpl;
    @Autowired
    private ErpMaterialService erpMaterialService; // 修正为使用接口而不是实现类
    @Autowired
    private ErpMaterialExtendService erpMaterialExtendService;
    @Autowired
    private ErpDepotItemService itemService;
    @Autowired
    private ErpMaterialCurrentStockService currentStockService;
    @Autowired
    private ErpRoleService roleService;
    @GetMapping("/find")
    public R<List<ErpMaterial>> find(){
        return R.success(erpMaterialServiceImpl.list());
    }
    @GetMapping("/findByPage")
    public R<Page<ErpMaterial>> findByPage (
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String categoryId,
            @RequestParam(required = false) String color,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String position,
            @RequestParam(required = false) String mfrs,
            @RequestParam(required = false) String weight,
            @RequestParam(required = false) String expiryNum,
            @RequestParam(required = false) String remark,
            @RequestParam(required = false) String enabled,
            @RequestAttribute("user") ErpUser user// 加入 tenantId 参数

    ){
        Page<ErpMaterial> page = new Page<>(current, size);
        try {

            page = erpMaterialServiceImpl.findByPage(page,
                    categoryId,color,keyword,position,mfrs,
                    weight,expiryNum,remark,enabled,user.getTenantId());
            return R.success(page);
        } catch (Exception e) {
            return R.fail("查询失败：" + e.getMessage());
        }
    }

@Log(operation = "商品信息添加", businessType = BusinessType.INSERT, isSaveRequestData = true, paramName = "user", jsonPath = "$.username")
@PostMapping("/add")
public R<String> addMaterial(@RequestBody MaterialRequest materialRequest,@RequestAttribute("user") ErpUser user) {

    // 创建 ErpMaterial 对象
    ErpMaterial material = materialRequest.getMaterial();

    // 设置默认信息
    material.setEnabled(true); // 例如，默认启用
    material.setDeleteFlag("0"); // 设置为未删除
    material.setTenantId(user.getTenantId()); // 假设 Tenant ID 默认值为 1
    // 其他默认值设置...
    // 添加商品
    boolean materialResult = erpMaterialService.addMaterial(materialRequest.getMaterial());

    // 如果商品添加成功，可以获取自动生成的ID
    if (materialResult) {
        // 这里可以通过查询或直接使用被保存的对象获取ID
        Long generatedId = materialRequest.getMaterial().getId(); // 这里将会返回null，因为id是未赋值的

        // 重新查询数据库获取刚插入的商品ID
        ErpMaterial savedMaterial = erpMaterialService.getById(materialRequest.getMaterial().getId());

        if (savedMaterial != null) {
            generatedId = savedMaterial.getId(); // 更新为新增商品的ID
        }

        // 添加扩展信息
        for (ErpMaterialExtend extend : materialRequest.getMaterialExtends()) {
            extend.setCreateTime(new Date());
            extend.setCreateSerial(user.getLoginName());
            extend.setTenantId(user.getTenantId());
            extend.setMaterialId(generatedId); // 将扩展信息与商品关联
            erpMaterialExtendService.addMaterialExtend(extend);
        }

        // 添加库存记录
        ErpMaterialCurrentStock stock = new ErpMaterialCurrentStock();
        stock.setMaterialId(generatedId); // 设置商品ID
        stock.setDepotId(null); // 设置仓库ID，假设为1，可以根据实际情况设置
        stock.setCurrentNumber(BigDecimal.valueOf(0)); // 初始化库存为0，或设置为其它默认值
        stock.setTenantId(user.getTenantId());
        stock.setDeleteFlag("0"); // 设置为未删除

        // 添加库存记录
        currentStockService.insertMaterial(stock);


        return R.success("添加成功"+generatedId);
    } else {
        return R.fail("添加失败");
    }
}

    @DeleteMapping("/delete/{id}")
    public Result<String> deleteMaterial(@PathVariable Long id) {
        boolean result = erpMaterialService.deleteMaterial(id);
        if (result) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    //    批量删除
    @DeleteMapping("/delete")
    public R deleteBatch(@RequestBody List<Long> ids) {
        for (Long id : ids) {
            erpMaterialServiceImpl.removeById(id);
        }
        return R.success();
    }

    // 获取最大条码
    @GetMapping("/max")
    public R<Long> getMaxBarCode(){
        Long maxBarCode = erpMaterialService.getMaxBarCode();

        return R.success(maxBarCode);
    }

    /**
     * 关联查询子单据
     * @param
     * @return
     */
    @GetMapping("/selectByMaterialId")
    public Result<List<ErpMaterialExtend>> findItems(@RequestParam("id") Long id){
        List<ErpMaterialExtend> erpDepotItems = erpMaterialExtendService.selectByMaterialId(id);
        return Result.success(erpDepotItems);
    }


    @GetMapping("/checkIfUsed/{id}")
    public Result<Long> checkIfUsed(@PathVariable Long id) {
        LambdaQueryWrapper<ErpDepotItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ErpDepotItem::getMaterialId, id);
        Long count = itemService.count(wrapper);// 检查商品是否被使用
        return Result.success(count); // 返回引用计数
    }
    @PutMapping("/update")
    public R<String> updateMaterial(@RequestBody MaterialRequest materialRequest, @RequestAttribute("user") ErpUser user) {
        // 获取商品信息
        ErpMaterial material = materialRequest.getMaterial();

        // 设置一些默认的信息
        material.setTenantId(user.getTenantId()); // 设置租户ID

        // 更新商品信息
        boolean result = erpMaterialService.updateMaterial(material);

        // 如果更新成功，处理扩展信息
        if (result) {
            // 先删除旧的扩展信息，再添加新的扩展信息
            erpMaterialExtendService.deleteByMaterialId(material.getId()); // 删除旧的扩展信息

            // 添加新的扩展信息
            for (ErpMaterialExtend extend : materialRequest.getMaterialExtends()) {
                extend.setCreateSerial(user.getLoginName());
                extend.setMaterialId(material.getId()); // 将扩展信息与商品关联
                erpMaterialExtendService.addMaterialExtend(extend);
            }
            return R.success("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }



    @GetMapping("/list")
    public R<Page<ErpMaterialDTO>> findByPage (
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long depotId,
        @RequestAttribute("user") ErpUser user// 加入 tenantId 参数

    ){
        Page<ErpMaterialDTO> page = new Page<>(current, size);
        try {

            page = erpMaterialService.selectAggregatedData(page,depotId, user.getTenantId()
            );
            return R.success(page);
        } catch (Exception e) {
            return R.fail("查询失败：" + e.getMessage());
        }
    }


@GetMapping("/aggregated")
public Result<List<ErpMaterialDTO>> getAggregatedMaterialData(
        @RequestParam(required = false) Long depotId,
        @RequestParam(required = false) Long headerId,
        @RequestAttribute("user") ErpUser user) {
    // 获取租户ID
    Long tenantId = user.getTenantId();

    // 查询数据
    List<ErpMaterialDTO> erpMaterialItems = erpMaterialService.select(depotId,headerId, tenantId);
    ErpRole role = roleService.getRoleByUserId(user.getId());
    if (StrUtil.contains("5", role.getPriceLimit())){
        List<String> names = Arrays.asList("commodityDecimal","allspice");
        erpMaterialItems.forEach(item -> {
            DTO.shieldPrice(item, names);
        });
    }
    // 返回结果
    return Result.success(erpMaterialItems);
}
    @GetMapping("/select2")
    public Result<List<ErpMaterialDTO>> getAggregatedMaterialDatas(
            @RequestParam(required = false) Long depotId,
            @RequestParam(required = false) Long materialId,
            @RequestAttribute("user") ErpUser user) {
        // 获取租户ID
        Long tenantId = user.getTenantId();

        // 查询数据
        List<ErpMaterialDTO> erpMaterialItems = erpMaterialService.select(depotId,materialId, tenantId);

        // 返回结果
        return Result.success(erpMaterialItems);
    }
}




